package s1_creatThread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/*
* 创建线程方式三：实现Callable接口
*
**/

//Callable接口是函数式接口，所以可以lambda表达式
//1、创建实现Callable接口的实现类
class MyCallable implements Callable<String> {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++){
            sum += i;
        }
        System.out.println("1-"+n+"的和为："+sum);
        return "1-"+n+"的和为："+sum;
    }
}
public class MyCallableDemo {
    public static void main(String[] args) throws Exception {
        //2、创建Callable接口实现类的对象
       MyCallable c = new MyCallable(100);
       MyCallable c1 = new MyCallable(10);
        //3、Callable对象封装成FutureTask对象-->未来任务对象
        FutureTask<String> ft = new FutureTask<>(c);
        FutureTask<String> ft1 = new FutureTask<>(c1);
        //4、FutureTask对象封装成线程对象，并启动线程
        Thread t = new Thread(ft);
        t.start();
        Thread t1 = new Thread(ft1);
        t1.start();

        try {
            System.out.println(ft.get());
            System.out.println(ft1.get());
            System.out.println("main线程执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

